import { Action, getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators';
import store from '@/store';
import { ConfigModel } from '@/models/config.model';
import { getConfigList } from '@/services/config.service';

@Module({ name: 'system', dynamic: true, namespaced: true, store })
export default class SystemStore extends VuexModule {
    private $config: SystemConfigModel = {
        title: 'EasyAdmin'
    };

    private $serverConfig: ConfigModel[] = [];
    private $keyServerConfig: any = {};


    public get config(): SystemConfigModel {
        return this.$config;
    }

    @Mutation
    public setConfig(val: SystemConfigModel) {
        this.$config = val;
    }

    /**
     * 获取节点配置值
     * @param key 键名：如 basic.title
     */
    public get getConfig(): (key: string) => any {
        return (key: string) => {
            return this.$keyServerConfig[key];
        }
    }

    public get serverConfig(): ConfigModel[] {
        return this.$serverConfig;
    }

    @Mutation
    private setServerConfig(data: ConfigModel[]) {
        this.$serverConfig = data;
        data.map(item => {
            if (item.grouping) {
                this.$keyServerConfig[item.grouping + '.' + item.key] = item.value;
            }
        });
    }

    @Action
    public getServerConfig() {
        return getConfigList()
            .then(result => {
                this.context.commit('setServerConfig', result.data);
            })
    }
}

export interface SystemConfigModel {
    title: string;
}

export const SystemModule = getModule(SystemStore);
